/*
 * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.matezk.dms.things.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.matezk.dms.things.mapper.ProductMapper;
import cn.matezk.dms.things.model.entity.ProductDO;
import cn.matezk.dms.things.model.entity.Property;
import cn.matezk.dms.things.model.query.ProductQuery;
import cn.matezk.dms.things.model.req.ProductReq;
import cn.matezk.dms.things.model.resp.ProductResp;
import cn.matezk.dms.things.service.ProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.continew.starter.core.exception.BusinessException;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.extension.crud.service.impl.BaseServiceImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * 产品服务实现
 *
 * @author 程道林
 * @since 2025/08/21 22:10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends BaseServiceImpl<ProductMapper, ProductDO, ProductResp, ProductResp, ProductQuery, ProductReq> implements ProductService {
    @Resource
    private ProductMapper productMapper;

    @Override
    public PageResp<ProductResp> page(ProductQuery query, PageQuery pageQuery) {
        QueryWrapper<ProductDO> queryWrapper = this.buildQueryWrapper(query);
        super.sort(queryWrapper, pageQuery);
        IPage<ProductResp> page = productMapper.selectPage(new Page<>(pageQuery.getPage(), pageQuery
            .getSize()), queryWrapper);
        PageResp<ProductResp> pageResp = PageResp.build(page, super.getListClass());
        pageResp.getList().forEach(this::fill);
        return pageResp;
    }

    @Override
    public ProductResp get(Long id) {
        return super.get(id);
    }


    @Override
    protected void beforeAdd(ProductReq req) {
        // 查询名称是否重复
        Long id = productMapper.selectByProductName(req.getProductName());
        if (ObjectUtil.isNotEmpty(id))
            throw new BusinessException("产品名称重复");
        String productId = productMapper.nextProductId();
        req.setProductId(productId);
        req.setProductSecret(RandomUtil.randomString(24));
        super.beforeAdd(req);
    }

    @Override
    protected void beforeUpdate(ProductReq req, Long id) {
        // 查询名称是否重复
        Long existsId = productMapper.selectByProductName(req.getProductName());
        if (ObjectUtil.isNotEmpty(existsId) && ObjectUtil.notEqual(id, existsId))
            throw new BusinessException("产品名称重复");
        // 校验标识符是否重复
        if (ObjectUtil.isNotEmpty(req.getModel())) {
            List<String> keys = new ArrayList<>();
            if (ObjectUtil.isNotEmpty(req.getModel().getProperties())) {
                for (Property p : req.getModel().getProperties()) {
                    if (keys.contains(p.getId()))
                        throw new BusinessException(String.format("标识符[%s]重复", p.getId()));
                    keys.add(p.getId());
                }
            }
        }
        super.beforeUpdate(req, id);
    }

    @Override
    protected void beforeDelete(List<Long> ids) {
        for (Long id : ids) {
            int count = productMapper.countDevice(id);
            if (count > 0) {
                throw new BusinessException("不允许的操作：产品下存在设备");
            }
        }
        super.beforeDelete(ids);
    }
}